<template>
  <div v-if="visible" class="post-detail-overlay" @click="handleOverlayClick">
    <div class="post-detail-modal" @click.stop>
      <!-- 弹窗头部 -->
      <div class="modal-header">
        <div class="header-left">
          <el-icon @click="handleClose" class="close-icon"><Close /></el-icon>
          <span class="modal-title">帖子详情</span>
        </div>
        <div class="post-actions">
          <el-icon @click="handleLike" class="action-icon" :class="{ liked: post.isLiked }">
            <Star />
          </el-icon>
          <el-icon @click="handleShare" class="action-icon">
            <Share />
          </el-icon>
        </div>
      </div>
      
      <!-- 帖子内容 -->
      <div class="post-content">
        <!-- 用户信息 -->
        <div class="post-header">
          <div class="user-info">
            <img :src="getUserAvatar(post)" :alt="post.userName || '匿名用户'" class="user-avatar" />
            <div class="user-details">
              <span class="user-name">{{ post.userName || '匿名用户' }}</span>
              <span class="post-time">{{ formatTime(post.createTime) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 帖子文本内容 -->
        <div class="post-text">
          <p>{{ post.content }}</p>
          
          <!-- 话题标签 -->
          <div v-if="post.topics && post.topics.length > 0" class="post-topics">
            <span 
              v-for="topic in post.topics" 
              :key="topic"
              class="topic-tag"
            >
              #{{ topic }}
            </span>
          </div>
        </div>
        
        <!-- 图片展示 -->
        <div v-if="post.images && post.images.length > 0" class="post-images">
          <div 
            v-for="(image, index) in post.images" 
            :key="index"
            class="image-item"
            :class="getImageClass(post.images.length)"
            @click="previewImage(image)"
          >
            <img :src="image" :alt="`图片${index + 1}`" class="post-image" />
            <div v-if="post.images.length > 9 && index === 8" class="more-images">
              +{{ post.images.length - 9 }}
            </div>
          </div>
        </div>
        
        <!-- 互动统计 -->
        <div class="post-stats">
          <span v-if="post.likeCount > 0" class="stat-item">
            <el-icon><Star /></el-icon>
            {{ post.likeCount }}人点赞
          </span>
          <span v-if="post.commentCount > 0" class="stat-item">
            <el-icon><ChatLineRound /></el-icon>
            {{ post.commentCount }}条评论
          </span>
          <span v-if="post.shareCount > 0" class="stat-item">
            <el-icon><Share /></el-icon>
            {{ post.shareCount }}次分享
          </span>
        </div>
      </div>
      
      <!-- 评论区域 -->
      <div class="comments-section">
        <div class="comments-header">
          <h4>评论 ({{ comments.length }})</h4>
        </div>
        
        <div class="comments-list">
          <div v-if="comments.length === 0" class="empty-comments">
            <p>暂无评论，快来抢沙发吧！</p>
          </div>
          <div 
            v-for="comment in comments" 
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-avatar">
              <img :src="comment.userAvatar" :alt="comment.userName" />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-user">{{ comment.userName }}</span>
                <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>
            </div>
          </div>
        </div>
        
        <!-- 评论输入 -->
        <div class="comment-input-section">
          <div class="input-container">
            <el-input 
              v-model="newComment.content" 
              placeholder="写下你的评论..."
              type="textarea"
              :rows="2"
              maxlength="200"
              show-word-limit
              class="comment-input"
            />
            <el-button 
              type="primary" 
              :disabled="!newComment.content.trim()"
              @click="handleSubmitComment"
              class="submit-btn"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Close, Star, Share, ChatLineRound } from '@element-plus/icons-vue'
import { getPostDetailApi, likePostApi, unlikePostApi, sharePostApi, getCommentsApi, addCommentApi } from '@/api/discover'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  postId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['close'])

// 用户store
const userStore = useUserStore()

// 当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id)

// 获取用户头像
const getUserAvatar = (post) => {
  // 如果是当前用户的帖子，使用用户信息中的头像
  if (post.userId === currentUserId.value && userStore.userInfo?.avatar) {
    return userStore.userInfo.avatar
  }
  // 否则使用帖子中的头像，如果没有则使用默认头像
  return post.userAvatar || '/src/assets/imgs/avatar_unlogin.png'
}

// 帖子数据
const post = ref({})
const comments = ref([])
const loading = ref(false)

// 新评论
const newComment = reactive({
  content: ''
})

// 获取帖子详情
const getPostDetail = async () => {
  if (!props.postId) return
  
  try {
    loading.value = true
    console.log('开始获取帖子详情，帖子ID:', props.postId)
    const response = await getPostDetailApi(props.postId)
    
    console.log('帖子详情API响应:', response)
    console.log('响应类型:', typeof response)
    if (response && typeof response === 'object') {
      console.log('响应键:', Object.keys(response))
    }
    
    // 简化响应处理
    if (response) {
      const postData = response.data || response
      console.log('帖子数据:', postData)
      
      post.value = {
        id: postData.id,
        content: postData.content,
        images: postData.images ? postData.images.map(img => img.imageUrl || img) : [],
        topics: postData.topics ? postData.topics.map(topic => topic.topicName || topic) : [],
        userName: postData.userName,
        userAvatar: postData.userAvatar,
        createTime: postData.createdAt,
        likeCount: postData.likeCount || 0,
        commentCount: postData.commentCount || 0,
        shareCount: postData.shareCount || 0,
        isLiked: postData.isLiked || false,
        privacy: postData.privacy,
        status: postData.status
      }
      
      console.log('处理后的帖子数据:', post.value)
      
      // 获取评论
      await getComments()
    } else {
      console.error('帖子详情响应为空')
      ElMessage.error('获取帖子详情失败')
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const getComments = async () => {
  if (!props.postId) return
  
  try {
    console.log('开始获取评论列表，帖子ID:', props.postId)
    const response = await getCommentsApi(props.postId, { page: 1, limit: 20 })
    
    console.log('评论API响应:', response)
    console.log('响应类型:', typeof response)
    if (response && typeof response === 'object') {
      console.log('响应键:', Object.keys(response))
    }
    
    // 简化响应处理
    if (response && response.data && response.data.comments && Array.isArray(response.data.comments)) {
      console.log('使用API返回的评论数据，数量:', response.data.comments.length)
      comments.value = response.data.comments
    } else if (response && Array.isArray(response)) {
      console.log('使用直接数组格式的评论数据，数量:', response.length)
      comments.value = response
    } else if (response && response.comments && Array.isArray(response.comments)) {
      console.log('使用response.comments格式的评论数据，数量:', response.comments.length)
      comments.value = response.comments
    } else {
      console.log('API返回数据格式不符合预期，使用模拟数据')
      console.log('实际响应内容:', response)
      // 模拟数据
      comments.value = [
        {
          id: 1,
          postId: props.postId,
          userId: 2,
          userName: '李四',
          userAvatar: '/src/assets/imgs/my_people.png',
          content: '看起来很不错！请问租金多少？',
          createdAt: new Date(Date.now() - 1800000).toISOString()
        },
        {
          id: 2,
          postId: props.postId,
          userId: 3,
          userName: '王五',
          userAvatar: '/src/assets/imgs/avatar_unlogin.png',
          content: '环境确实不错，交通方便吗？',
          createdAt: new Date(Date.now() - 900000).toISOString()
        }
      ]
    }
    
    console.log('最终评论数据:', comments.value)
  } catch (error) {
    console.error('获取评论列表失败:', error)
    // 使用模拟数据
    comments.value = [
      {
        id: 1,
        postId: props.postId,
        userId: 2,
        userName: '李四',
        userAvatar: '/src/assets/imgs/my_people.png',
        content: '看起来很不错！请问租金多少？',
        createdAt: new Date(Date.now() - 1800000).toISOString()
      },
      {
        id: 2,
        postId: props.postId,
        userId: 3,
        userName: '王五',
        userAvatar: '/src/assets/imgs/avatar_unlogin.png',
        content: '环境确实不错，交通方便吗？',
        createdAt: new Date(Date.now() - 900000).toISOString()
      }
    ]
  }
}

// 提交评论
const handleSubmitComment = async () => {
  if (!newComment.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  try {
    const commentData = {
      content: newComment.content
    }
    
    const response = await addCommentApi(props.postId, commentData)
    
    if (response && (response.code === 0 || response.code === 200)) {
      ElMessage.success('评论发布成功')
      newComment.content = ''
      // 重新获取评论列表
      await getComments()
      // 更新评论数
      post.value.commentCount++
    } else {
      ElMessage.error(response?.message || '评论发布失败')
    }
  } catch (error) {
    console.error('评论发布失败:', error)
    ElMessage.error('评论发布失败，请重试')
  }
}

// 点赞帖子
const handleLike = async () => {
  try {
    if (post.value.isLiked) {
      await unlikePostApi(post.value.id)
      post.value.likeCount--
      post.value.isLiked = false
      ElMessage.success('取消点赞')
    } else {
      await likePostApi(post.value.id)
      post.value.likeCount++
      post.value.isLiked = true
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 分享帖子
const handleShare = async () => {
  try {
    await sharePostApi(post.value.id)
    post.value.shareCount++
    ElMessage.success('分享成功')
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败，请重试')
  }
}

// 预览图片
const previewImage = (imageUrl) => {
  // 这里可以实现图片预览功能
  ElMessage.info('图片预览功能开发中...')
}

// 获取图片布局类名
const getImageClass = (count) => {
  if (count === 1) return 'single'
  if (count === 2) return 'double'
  if (count === 3) return 'triple'
  if (count === 4) return 'quad'
  return 'multiple'
}

// 格式化时间
const formatTime = (timeString) => {
  const time = new Date(timeString)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) { // 1天内
    return Math.floor(diff / 3600000) + '小时前'
  } else {
    return Math.floor(diff / 86400000) + '天前'
  }
}

// 关闭弹窗
const handleClose = () => {
  newComment.content = ''
  emit('close')
}

// 点击遮罩层关闭
const handleOverlayClick = () => {
  handleClose()
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal && props.postId) {
    getPostDetail()
  }
})
</script>

<style scoped>
.post-detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.post-detail-modal {
  background-color: #fff;
  border-radius: 16px;
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.close-icon {
  font-size: 20px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.close-icon:hover {
  color: #333;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.post-actions {
  display: flex;
  gap: 16px;
}

.action-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-icon:hover {
  color: #4CAF50;
  transform: scale(1.1);
}

.action-icon.liked {
  color: #e74c3c;
}

.post-content {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.post-header {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-text {
  margin-bottom: 16px;
}

.post-text p {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin: 0 0 8px 0;
}

.post-topics {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.topic-tag {
  padding: 2px 8px;
  background-color: #e8f5e8;
  color: #4CAF50;
  border-radius: 12px;
  font-size: 12px;
}

.post-images {
  margin-bottom: 16px;
  display: grid;
  gap: 4px;
}

.image-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-item:hover {
  transform: scale(1.02);
}

.post-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.more-images {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

/* 图片布局 */
.post-images .single {
  grid-column: 1;
  aspect-ratio: 16/9;
}

.post-images .double {
  grid-template-columns: 1fr 1fr;
  aspect-ratio: 1;
}

.post-images .triple {
  grid-template-columns: 1fr 1fr 1fr;
  aspect-ratio: 1;
}

.post-images .quad {
  grid-template-columns: 1fr 1fr;
  aspect-ratio: 1;
}

.post-images .multiple {
  grid-template-columns: repeat(3, 1fr);
  aspect-ratio: 1;
}

.post-stats {
  display: flex;
  gap: 16px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.comments-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.comments-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.comments-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.comments-list {
  flex: 1;
  padding: 16px 20px;
  overflow-y: auto;
}

.empty-comments {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.comment-user {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.comment-input-section {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #f8f9fa;
  flex-shrink: 0;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.comment-input {
  flex: 1;
}

.submit-btn {
  height: 36px;
  padding: 0 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-detail-overlay {
    padding: 10px;
  }
  
  .post-detail-modal {
    max-height: 95vh;
  }
  
  .post-content {
    padding: 16px;
  }
  
  .comments-list {
    padding: 12px 16px;
  }
  
  .comment-input-section {
    padding: 12px 16px;
  }
  
  .input-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .submit-btn {
    width: 100%;
    height: 40px;
  }
}
</style>
